package main

import (
	"fmt"
	"io"
	"net"
	"sync"
	"time"
)

func main() {
	timeStr := time.Now().Format("2006-01-02 15:04:05")
	fmt.Println(timeStr)
	startT := time.Now() //计算当前时间
	//return
	maxNum := 800
	var GNum sync.WaitGroup
	GNum.Add(1)
	for i := 0; i < 1; i++ {
		go func() {
			conn, err := net.Dial("tcp", "127.0.0.1:8008")
			if err != nil {
				fmt.Println("client start err, exit!", err)
				return
			}
			var index int
			for {
				//发封包message消息
				dp := fullserver.NewDataPack()

				requestMsg := &pb.CAuth{Token: "04FuwJkAxdkFXHcM"}

				data, _ := proto.Marshal(requestMsg)

				msg, _ := dp.Pack(fullserver.NewMsgPackage(51, data, 1, 39817, 1, 1, 1))
				_, err2 := conn.Write(msg)
				if err2 != nil {
					fmt.Println("write error err ", err2)
					return
				}

				//先读出流中的head部分
				headData := make([]byte, dp.GetHeadLen())
				_, err = io.ReadFull(conn, headData) //ReadFull 会把msg填充满为止
				if err != nil {
					fmt.Println("read head error")
				}
				//将headData字节流 拆包到msg中
				msgHead, err3 := dp.Unpack(headData)
				if err3 != nil {
					fmt.Println("server unpack err:", err3)
					return
				}

				if msgHead.GetDataLen() > 0 {
					//msg 是有data数据的，需要再次读取data数据
					msghead := msgHead.(*fullserver.Message)
					msghead.Data = make([]byte, msghead.GetDataLen())

					//根据dataLen从io中读取字节流
					_, err4 := io.ReadFull(conn, msghead.Data)
					if err4 != nil {
						fmt.Println("server unpack data err:", err4)
						return
					}

					//response := &pb.SSetLayPosition{}
					response := &pb.SJumpGameWaitLine{}
					//response := &pb.SError{}
					proto.Unmarshal(msghead.Data, response)
					if msghead.ID == 52 {
						fmt.Println("==> Test Router:[Ping] Recv Msg: ID=", msghead.ID, ", len=", msghead.DataLen, ", data=", response)
					}
					index++
					if index > maxNum {
						time.Sleep(time.Second * 1)
						conn.Close()
						break
					}
				}
			}
			GNum.Done()
		}()
	}
	GNum.Wait()
	tc := time.Since(startT) //计算耗时
	fmt.Printf("time cost = %v\n", tc)

}
